package JUC;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 豆包LU
 * @date 2023/5/8 16:26
 */
public class ProducerConsumer {
    private static int[] buffer = new int[1]; // 仓库
    private static int count = 0; // 仓库中物品数量

    // 创建线程池
    private static ExecutorService executor = Executors.newFixedThreadPool(2);

    // 生产者线程
    static class Producer implements Runnable {
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (buffer) { // 获取仓库的锁
                    while (count == buffer.length) { // 如果仓库已经满了
                        try {
                            buffer.wait(); // 生产者等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    buffer[count++] = i; // 生产物品并放入仓库中
                    System.out.println("Produced " + i);
                    buffer.notifyAll(); // 唤醒其他等待中的线程
                }
            }
        }
    }

    // 消费者线程
    static class Consumer implements Runnable {
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (buffer) { // 获取仓库的锁
                    while (count == 0) { // 如果仓库已经空了
                        try {
                            buffer.wait(); // 消费者等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int item = buffer[--count]; // 从仓库中取出物品
                    System.out.println("Consumed " + item);
                    buffer.notifyAll(); // 唤醒其他等待中的线程
                }
            }
        }
    }

    public static void main(String[] args) {
        executor.execute(new Producer()); // 启动生产者线程
        executor.execute(new Consumer()); // 启动消费者线程
        executor.shutdown(); // 关闭线程池
    }
}

